package com.asom.player;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.actionbar.R;

public class CustomActionBar extends ActionBar {

	private EditText mTextInput;
	private View mTitleMoreIndicator;

	public CustomActionBar(Context context, AttributeSet attrs) {
		super(context, attrs);

		mTitleMoreIndicator = mBarView
				.findViewById(R.id.actionbar_title_is_more);
		mTextInput = (EditText) mBarView
				.findViewById(R.id.actionbar_text_input);
	}

	/**
	 * Adds a new {@link View} at the specified index. Use carefully, and add a
	 * tag to the view, if you want to remove it later.(The tag should be an
	 * Action)
	 * 
	 * @param view
	 *            the view to add
	 * @param index
	 *            the position at which to add the action
	 */
	public void addCustomView(View view, int index) {
		mActionsView.addView(view, index);
	}

	protected ActionList mSavedActions;
	private CharSequence mSavedTitle;
	private Action mSavedHomeAction;

	/**
	 * Saves current state, but does not save custom Views.
	 */
	public void saveState() {
		if (mSavedActions != null)
			mSavedActions.clear();
		else
			mSavedActions = new ActionList();
		int childCount = mActionsView.getChildCount();
		for (int i = 0; i < childCount; i++) {
			View view = mActionsView.getChildAt(i);
			if (view != null) {
				final Object tag = view.getTag();
				if (tag instanceof Action) {
					mSavedActions.add((Action) tag);
				}
			}
		}
		if (mTitleView != null)
			mSavedTitle = mTitleView.getText();
		if (mHomeBtn != null)
			mSavedHomeAction = (Action) mHomeBtn.getTag();
	}

	/**
	 * Saves current state, but does not save custom Views.
	 */
	public View getActionView(Action action) {
		if (action.equals(mHomeBtn.getTag()))
			return mHomeBtn;
		View view;
		int childCount = mActionsView.getChildCount();
		for (int i = 0; i < childCount; i++) {
			view = mActionsView.getChildAt(i);
			if (view != null) {
				final Object tag = view.getTag();
				if (tag instanceof Action) {
					if (action.equals(tag))
						return view;
				}
			}
		}
		return null;
	}

	public void setDisplayTitleAsMoreEnabled(boolean show) {
		mTitleMoreIndicator.setVisibility(show ? View.VISIBLE : View.GONE);
	}

	public void setActionDrawable(int index, int resId) {

		View view = mActionsView.getChildAt(index);

		ImageButton labelView = (ImageButton) view
				.findViewById(R.id.actionbar_item);
		labelView.setImageResource(resId);
	}

	/**
	 * Restores saved state, but with no custom Views Removes save point.
	 */
	public void restoreState() {
		removeAllActions();

		if (mSavedActions != null) {
			addActions(mSavedActions);
			mSavedActions.clear();
		}
		if (mSavedTitle != null)
			setTitle(mSavedTitle);
		if (mSavedHomeAction != null)
			setHomeAction(mSavedHomeAction);

		mSavedActions = null;
		mSavedTitle = null;
		mSavedHomeAction = null;
	}

	public void dismissInput() {
		Utils.hideSoftKeyboard(this);
		setInputVisibility(false);
		restoreState();
		try {
			throw new Exception();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Make the actions zone take the whole actionBar. Good in situations like
	 * putting a search edit box.
	 * 
	 * @param fill
	 *            for activating or deactivating
	 */
	public void setInputVisibility(boolean visible) {
		if (visible) {
			mTextInput.setVisibility(View.VISIBLE);
			// TODO: nu stiu daca verificarea asta este tocmai corecta. In caz
			// ca apar 2 search-bar-uri, asta ar cam fi cauza
			if (!mActionsView.equals(mTextInput.getParent()))
				mActionsView.addView(mTextInput);
			mActionsView.getLayoutParams().width = ViewGroup.LayoutParams.FILL_PARENT;
			mTextInput.requestFocus();

			((InputMethodManager) mTextInput.getContext().getSystemService(
					Context.INPUT_METHOD_SERVICE)).showSoftInput(mTextInput, 0);

		} else {
			mActionsView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
			mTextInput.setText("");
			mTextInput.setVisibility(View.INVISIBLE);
		}
	}

	public CharSequence getInputValue() {
		return mTextInput.getText();
	}

	// public static class SelectAllAction extends AbstractAction {
	//
	// SongGroup songGroup;
	//		
	// public SelectAllAction(SongGroup songListAdapter) {
	// super(R.drawable.btn_check_buttonless_on);
	// this.songGroup =songListAdapter;
	// }
	//
	// @Override
	// public void performAction(View view) {
	// if (songGroup!=null)
	// songGroup.selectAll();
	// }
	// }
	//	
	// public static class SelectNoneAction extends AbstractAction {
	//
	// SongGroup songGroup;
	//		
	// public SelectNoneAction(SongGroup songListAdapter) {
	// super(R.drawable.btn_check_buttonless_off);
	// this.songGroup =songListAdapter;
	// }
	//
	// @Override
	// public void performAction(View view) {
	// if (songGroup!=null)
	// songGroup.selectNone();
	// }
	// }
	//	
	// public static class DownloadAllAction extends AbstractAction {
	//
	// SongGroup songGroup;
	// Context context;
	//		
	// public DownloadAllAction(Context context,SongGroup songGroup) {
	// super(R.drawable.loading);
	// this.songGroup =songGroup;
	// this.context=context;
	// }
	//
	// @Override
	// public void performAction(View view) {
	// if (songGroup!=null)
	// {
	//				
	// ArrayList<SogouSong> job = songGroup.getAllSelected();
	// if (job!=null)
	// if (job.size()>0)
	// {
	// Bundle toSend = new Bundle();
	// toSend.putParcelableArrayList("songs", job);
	// Intent launchService = new Intent(context,DownloadSongsService.class);
	// launchService.putExtras(toSend);
	// context.startService(launchService);
	// return;
	// }
	// Toast.makeText(context, "Please make a selection first",
	// Toast.LENGTH_LONG).show();
	// }
	// }
	// }

	public static class ShowSearchAction extends AbstractAction {
		CustomActionBar aBar;

		public ShowSearchAction(CustomActionBar aBar) {
			super(R.drawable.ic_title_search_default);
			this.aBar = aBar;
		}

		@Override
		public void performAction(View view) {
			aBar.saveState();
			aBar.removeAllActions();
			aBar.setTitle("");
			aBar.clearHomeAction();

			aBar.setInputVisibility(true);
			aBar.addAction(new SimpleSearchAction(aBar));

			// aBar.mTextInput.setOnFocusChangeListener(new
			// OnFocusChangeListener() {
			//				
			// @Override
			// public void onFocusChange(View v, boolean hasFocus) {
			// if (!hasFocus)
			// aBar.dismissInput();
			// }
			// });
			// aBar.mTextInput.setOnKeyListener(new OnKeyListener() {
			//				
			// @Override
			// public boolean onKey(View v, int keyCode, KeyEvent event) {
			// if (keyCode == KeyEvent.KEYCODE_BACK)
			// aBar.dismissInput();
			// return false;
			// }
			// });
		}
	}

	public static class SimpleSearchAction extends AbstractAction {
		// EditText searchWords;
		CustomActionBar aBar;

		SimpleSearchAction(CustomActionBar aBar) {
			super(R.drawable.ic_title_search_default);

			this.aBar = aBar;
			final CustomActionBar finalBar = aBar;

			aBar.mTextInput.setOnKeyListener(new OnKeyListener() {
				/**
				 * This listens for the user to press the enter button on the
				 * keyboard and then hides the virtual keyboard
				 */
				public boolean onKey(View view, int key, KeyEvent event) {
					// If the event is a key-down event on the "enter" button
					if ((event.getAction() == KeyEvent.ACTION_DOWN)
							&& (key == KeyEvent.KEYCODE_ENTER)) {
						String input = finalBar.getInputValue().toString();

						if (input.length() >= 2) {

							Intent newSearch = new Intent(view.getContext(),
									ListActivity.class);
							newSearch.putExtra("category", "Search");
							newSearch.putExtra("searchParameter", input);

							finalBar.getContext().startActivity(newSearch);

							Utils.hideSoftKeyboard(view);
							finalBar.setInputVisibility(false);
							finalBar.restoreState();
							
							return true;
						} else {
							Toast toast = Toast.makeText(view.getContext(),
									"Type in at least 2 characters",
									Toast.LENGTH_SHORT);
							toast.setGravity(Gravity.TOP, 0, 0);
							toast.show();
							
							return false;
						}
					}
					return false;
				}
			});
		}

		@Override
		public void performAction(View view) {

			String input = aBar.getInputValue().toString();

			if (input.length() >= 2) {

				Intent newSearch = new Intent(view.getContext(),
						ListActivity.class);
				newSearch.putExtra("category", "Search");
				newSearch.putExtra("searchParameter", input);

				aBar.getContext().startActivity(newSearch);

				Utils.hideSoftKeyboard(view);
				aBar.setInputVisibility(false);
				aBar.restoreState();
				aBar = null;
			} else {
				Toast toast = Toast.makeText(view.getContext(),
						"Type in at least 2 characters", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.TOP, 0, 0);
				toast.show();
			}
		}
	}

}
